package model

import (
	ryrpc "admin/rpc"

	"github.com/meilisearch/meilisearch-go"
)

type SmsData_t struct {
	D []ryrpc.TblSmsLog `json:"d" cbor:"d"`
	T int64             `json:"total" cbor:"t"`
	S uint              `json:"s" cbor:"s"`
}

func SmsList(page, pageSize int, filter string) (SmsData_t, error) {

	data := SmsData_t{}

	offset_t := pageSize * (page - 1)

	index := meta.Meili.Index("smslog")

	cond := &meilisearch.SearchRequest{
		Limit:  int64(pageSize),
		Offset: int64(offset_t),
	}

	cond.Filter = filter
	cond.Sort = []string{"ts:desc"}
	searchRes, err := index.Search("", cond)
	if err != nil {
		return data, err
	}
	ll := len(searchRes.Hits)
	if ll == 0 {
		data.S = 0
		data.T = 0
		return data, err
	}
	data.D = make([]ryrpc.TblSmsLog, ll)
	data.T = searchRes.EstimatedTotalHits
	data.S = uint(pageSize)

	for i, v := range searchRes.Hits {
		val := v.(map[string]interface{})

		data.D[i].ID = val["id"].(string)
		data.D[i].Ty = val["ty"].(string)
		data.D[i].State = val["state"].(string)
		data.D[i].Source = val["source"].(string)
		data.D[i].IP = val["ip"].(string)
		data.D[i].Phone = val["phone"].(string)
		data.D[i].Flags = val["flags"].(string)
		data.D[i].Code = val["code"].(string)
		data.D[i].CreateAt = int64(val["create_at"].(float64))
		data.D[i].UpdatedAt = int64(val["updated_at"].(float64))
	}

	return data, nil
}

func SmsFlushAll() {

	filterab := []string{
		"ty",
		"state",
		"create_at",
		"phone",
	}
	sortable := []string{
		"ts",
	}
	searchable := []string{
		"phone",
	}

	meta.Meili.DeleteIndex("smslog")
	index := meta.Meili.Index("smslog")
	index.UpdateFilterableAttributes(&filterab)
	index.UpdateSortableAttributes(&sortable)
	index.UpdateSearchableAttributes(&searchable)
}
